/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.account;

import cn.hutool.crypto.SecureUtil;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.spring.SpringContextHolder;
import com.je.common.base.util.DateUtils;
import com.je.common.base.util.SecurityUserHolder;
import com.je.common.base.util.SystemSecretUtil;
import com.je.ibatis.extension.plugins.inner.tenant.DynaTenant;
import com.je.ibatis.extension.plugins.inner.tenant.DynaTenantContext;
import com.je.rbac.config.SaaSConfig;
import com.je.rbac.exception.AccountException;
import com.je.rbac.exception.LoginException;
import com.je.rbac.rpc.AccountRpcService;
import com.je.rbac.service.account.RbacAccountService;
import com.je.rbac.service.account.RbacLoginService;
import com.je.rbac.service.company.RbacDepartmentService;
import com.je.rbac.service.log.RbacLoginLogService;
import com.je.rbac.service.organization.OrgType;
import com.je.rbac.service.organization.RbacOrganizationService;
import com.je.rbac.service.secret.SecretSettingService;
import com.je.rbac.util.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping(value = "/je/rbac/cloud/login")
public class RbacLoginController extends AbstractPlatformController {

    /**
     * 最大验证次数
     */
    private static final int DEFAULT_MAX_VERIFY_TIMES = 5;
    /**
     * 错误次数的Key
     */
    public static final String ERROR_TIMES_KEY_TEMPLATE = "errorTimes/%s";
    /**
     * 需要修改密码标志
     */
    public static final String USER_NEED_MODIFY_PASSWORD_TEMPALTE = "needModifyPassword/%s";
    @Autowired
    private SaaSConfig saaSConfig;
    @Autowired
    private RbacLoginService rbacLoginService;
    @Autowired
    private RbacAccountService rbacAccountService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;
    @Autowired
    private AccountRpcService accountRpcService;
    @Autowired
    private RbacLoginLogService rbacLoginLogService;
    @Autowired
    private RbacDepartmentService rbacDepartmentService;
    @Autowired
    private RbacOrganizationService rbacOrganizationService;
    @Autowired
    private SecretSettingService secretSettingService;

    @RequestMapping(value = {"/checkLogin"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult<String> checkLogin() {
        if (!rbacLoginService.checkLogin()) {
            return BaseRespResult.errorResult("未登录，请执行登录！");
        }
        return BaseRespResult.successResult("用户已登录！");
    }

    @RequestMapping(value = {"/sendNote"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<String> sendNote(HttpServletRequest request) {
        String phone = getStringParameter(request, "phone");
        String device = getStringParameter(request, "device");
        if (Strings.isNullOrEmpty(phone) || Strings.isNullOrEmpty(device)) {
            return BaseRespResult.errorResult("手机号或验证码错误！");
        }
        DynaBean accountBean = accountRpcService.findAccountByPhone(phone);
        if (accountBean == null) {
            return BaseRespResult.errorResult("手机号或验证码错误！");
        }

        try {
            String randomStr = rbacLoginService.sendRandom(accountBean, device);
            return BaseRespResult.successResult(randomStr);
        } catch (LoginException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    @RequestMapping(value = {"/thirdTempCode"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult thirdTempCode(HttpServletRequest request) {
        String tempCode = getStringParameter(request, "tempCode");
        return BaseRespResult.successResult(redisTemplate.opsForValue().get("thirdLoginCode/" + tempCode));
    }

    /***
     * 短信登录
     * @param request
     * @return
     */
    @RequestMapping(value = {"/noteLogin"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult noteLogin(HttpServletRequest request) {
        String phone = getStringParameter(request, "phone");
        String captcha = getStringParameter(request, "captcha");
        String device = getStringParameter(request, "device");
        String deptId = getStringParameter(request, "deptId");
        String tenantId = getStringParameter(request, "tenantId");

        String enablePhoneCaptchaLogin = systemSettingRpcService.findSettingValue("JE_CORE_PHONELOGIN");
        if (!"1".equals(enablePhoneCaptchaLogin)) {
            return BaseRespResult.errorResult("非法的登录方式，请联系管理员！");
        }

        if (Strings.isNullOrEmpty(phone) || Strings.isNullOrEmpty(captcha) || Strings.isNullOrEmpty(device)) {
            return BaseRespResult.errorResult("手机号或验证码错误！");
        }

        DynaBean accountBean;
        if (saaSConfig.enableSaas()) {
            //多租户方式
            if (Strings.isNullOrEmpty(tenantId)) {
                List<DynaBean> accountBeanList = accountRpcService.findAllTenantAccount("PHONE", phone);
                if (accountBeanList == null || accountBeanList.isEmpty()) {
                    return BaseRespResult.errorResult("不存在的账号！");
                }
                if (accountBeanList.size() == 1) {
                    accountBean = accountBeanList.get(0);
                } else {
                    List<Map<String, Object>> tenantMapList = new ArrayList<>();
                    Map<String, Object> eachMap;
                    for (DynaBean eachTenantBean : accountBeanList) {
                        eachMap = new HashMap<>();
                        eachMap.put("id", eachTenantBean.getStr("SY_TENANT_ID"));
                        eachMap.put("name", eachTenantBean.getStr("SY_TENANT_NAME"));
                        tenantMapList.add(eachMap);
                    }
                    return BaseRespResult.successResult(tenantMapList, "5000", "请选择租户！");
                }
            } else {
                accountBean = accountRpcService.findTenantAccount("PHONE", tenantId, phone);
            }
        } else {
            try {
                accountBean = accountRpcService.findLoginAccountByType("PHONE", phone);
            } catch (AccountException e) {
                return BaseRespResult.errorResult(e.getMessage());
            }
        }

        if (accountBean == null) {
            return BaseRespResult.errorResult("手机号或验证码错误！");
        }
        setTenantContext(accountBean);

        if (!rbacLoginService.checkRandom(accountBean, captcha, device)) {
            return BaseRespResult.errorResult("手机号或验证码错误！");
        }

        try {
            //校验账号有效期
            if (!Strings.isNullOrEmpty(accountBean.getStr("ACCOUNT_EXPIRE_TIME"))) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DAFAULT_DATETIME_FORMAT);
                    String dateStr = sdf.format(new Date());
                    Date currrentTime = new SimpleDateFormat(DateUtils.DAFAULT_DATETIME_FORMAT).parse(dateStr);
                    Date expireTime = new SimpleDateFormat(DateUtils.DAFAULT_DATETIME_FORMAT).parse(accountBean.getStr("ACCOUNT_EXPIRE_TIME"));
                    if (expireTime.getTime() < currrentTime.getTime()) {
                        return BaseRespResult.errorResult("该账号已过期，请联系管理员！");
                    }
                } catch (ParseException e) {
                    return BaseRespResult.errorResult("校验账号有效期异常！");
                }
            } else {
                if (Strings.isNullOrEmpty(accountBean.getStr("ACCOUNT_PERMANENT_CODE")) ||
                        "0".equals(accountBean.getStr("ACCOUNT_PERMANENT_CODE"))) {
                    return BaseRespResult.errorResult("该账号已过期，请联系管理员！");
                }
            }
            //登录需判断机构类型是 外部机构 还是 公司员工
            //该账号所属机构是外部机构
            if (!rbacAccountService.checkOrgTypeByAccountId(accountBean.getStr("JE_RBAC_ACCOUNT_ID"))) {
                String token = rbacLoginService.login(tenantId, deptId, accountBean, device, "2");
                return BaseRespResult.successResult(token, "登录成功！");
            }
            if (!Strings.isNullOrEmpty(deptId)) {
                //校验当前部门是否有效
                DynaBean deptBean = rbacDepartmentService.findById(deptId);
                if (deptBean == null) {
                    return BaseRespResult.errorResult("获取人员部门异常！");
                }
                //判断该部门人员 是否允许访问系统：查找部门账号表是否存在
                DynaBean accountDeptBean = rbacLoginService.findAccountDept(accountBean.getStr("JE_RBAC_ACCOUNT_ID"), deptId);
                if (accountDeptBean == null || accountDeptBean.getStr("SY_STATUS").equals("0")) {
                    return BaseRespResult.errorResult("该人员部门未开通访问权限，请重新选择！");
                }
                String token = rbacLoginService.login(tenantId, deptId, accountBean, device, "2");
                return BaseRespResult.successResult(token, "登录成功！");
            }
            List<Map<String, Object>> departments = rbacLoginService.checkDepartment(accountBean);
            if (departments == null) {
                return BaseRespResult.errorResult("获取人员部门异常！");
            }
            if (departments.size() > 1) {
                return BaseRespResult.successResult(departments, "5001", "请选择部门！");
            }
            deptId = (String) departments.get(0).get("id");
            String token = rbacLoginService.login(tenantId, deptId, accountBean, device, "2");
            //账号解除锁定
            rbacAccountService.unlockAccount(accountBean.getStr("JE_RBAC_ACCOUNT_ID"));
            initUserSecretContext(request);
            return BaseRespResult.successResult(token, "登录成功！");
        } catch (LoginException e) {
            return BaseRespResult.errorResult(e.getMessage());
        } catch (AccountException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    /**
     * 初始化用户密级上下文
     * @param request
     */
    private void initUserSecretContext(HttpServletRequest request) {
        if (!SystemSecretUtil.isOpen()) {
            return;
        }
        String agentIp = IpUtil.getIpAddress(request);
        String accountId = SecurityUserHolder.getCurrentAccountId();
        secretSettingService.requireUserContextSecretInfo(agentIp, accountId);
    }

    /**
     * 账号密码登录
     * status:
     * 1000 登录成功
     * 5000 需要选择租户
     * 5001 需要选择部门
     * 5002 需要校验验证码
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/accountLogin"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult accountLogin(HttpServletRequest request) {
        String account = getStringParameter(request, "account");
        String deptId = getStringParameter(request, "deptId");
        String password = getStringParameter(request, "password");
        String device = getStringParameter(request, "device");
        String tenantId = getStringParameter(request, "tenantId");
        String code = getStringParameter(request, "code");

        if (Strings.isNullOrEmpty(account) || (Strings.isNullOrEmpty(password) && Strings.isNullOrEmpty(code))) {
            return BaseRespResult.errorResult("账号或密码错误，请重新登录！");
        }

        String verifyType = systemSettingRpcService.findSettingValue("JE_CORE_VERIFY");
        if (Strings.isNullOrEmpty(verifyType)) {
            return BaseRespResult.errorResult("系统设置错误，请在系统设置中设置登录方式！");
        }

        DynaBean accountBean;
        if (saaSConfig.enableSaas()) {
            //多租户方式
            if (Strings.isNullOrEmpty(tenantId)) {
                List<DynaBean> accountBeanList = accountRpcService.findAllTenantAccount(verifyType, account);
                if (accountBeanList == null || accountBeanList.isEmpty()) {
                    return BaseRespResult.errorResult("不存在的账号！");
                }
                if (accountBeanList.size() == 1) {
                    accountBean = accountBeanList.get(0);
                } else {
                    List<Map<String, Object>> tenantMapList = new ArrayList<>();
                    Map<String, Object> eachMap;
                    for (DynaBean eachTenantBean : accountBeanList) {
                        eachMap = new HashMap<>();
                        eachMap.put("id", eachTenantBean.getStr("SY_TENANT_ID"));
                        eachMap.put("name", eachTenantBean.getStr("SY_TENANT_NAME"));
                        tenantMapList.add(eachMap);
                    }
                    return BaseRespResult.successResult(tenantMapList, "5000", "请选择租户！");
                }
            } else {
                accountBean = accountRpcService.findTenantAccount(verifyType, tenantId, account);
            }
        } else {
            try {
                accountBean = accountRpcService.findLoginAccountByType(verifyType, account);
            } catch (AccountException e) {
                return BaseRespResult.errorResult(e.getMessage());
            }
        }

        if (accountBean == null) {
            return BaseRespResult.errorResult("账号或密码错误，请重新登录！");
        }
        //设置租户上下文
        setTenantContext(accountBean);

        //校验账号状态是否正常
        if ("0".equals(accountBean.get("SY_STATUS"))) {
            return BaseRespResult.errorResult("该账号已禁用，请联系管理员！");
        }
        //校验账号是否锁定
        if ("0".equals(accountBean.get("ACCOUNT_LOCKED_STATUS"))) {
            return BaseRespResult.errorResult("该账号已锁定，请使用其他方式登录或联系管理员解锁！");
        }
        //校验账号有效期
        if (!Strings.isNullOrEmpty(accountBean.getStr("ACCOUNT_EXPIRE_TIME"))) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DAFAULT_DATETIME_FORMAT);
                String dateStr = sdf.format(new Date());
                Date currrentTime = new SimpleDateFormat(DateUtils.DAFAULT_DATETIME_FORMAT).parse(dateStr);
                Date expireTime = new SimpleDateFormat(DateUtils.DAFAULT_DATETIME_FORMAT).parse(accountBean.getStr("ACCOUNT_EXPIRE_TIME"));
                if (expireTime.getTime() < currrentTime.getTime()) {
                    return BaseRespResult.errorResult("该账号已过期，请联系管理员！");
                }
            } catch (ParseException e) {
                return BaseRespResult.errorResult("校验账号有效期异常！");
            }
        } else {
            if (Strings.isNullOrEmpty(accountBean.getStr("ACCOUNT_PERMANENT_CODE")) ||
                    "0".equals(accountBean.getStr("ACCOUNT_PERMANENT_CODE"))) {
                return BaseRespResult.errorResult("该账号已过期，请联系管理员！");
            }
        }

        if (Strings.isNullOrEmpty(code)) {
            //校验密码
            if (!accountBean.getStr("ACCOUNT_PASSWORD").equals(SecureUtil.md5(password))) {
                String settingTimes = systemSettingRpcService.findSettingValue("JE_CORE_ERRORPW");
                int calcedTimes;
                if (!Strings.isNullOrEmpty(settingTimes)) {
                    calcedTimes = Integer.valueOf(settingTimes);
                } else {
                    calcedTimes = DEFAULT_MAX_VERIFY_TIMES;
                }
                long times = redisTemplate.opsForValue().increment(String.format(ERROR_TIMES_KEY_TEMPLATE, accountBean.getStr("JE_RBAC_ACCOUNT_ID")));
                if (times > calcedTimes) {
                    //锁定该登录账号
                    rbacAccountService.lockAccount(accountBean.getStr("JE_RBAC_ACCOUNT_ID"), -1);
                    return BaseRespResult.errorResult(String.format("账号或密码超过%s次，账号已锁定，请使用其他方式登录！", calcedTimes));
                }
                return BaseRespResult.errorResult(String.format("账号或密码错误，您还剩余%s次登录机会！", calcedTimes - times));
            }
        } else {
            if (!redisTemplate.hasKey("thirdLoginCode/" + code)) {
                return BaseRespResult.errorResult("临时授权码不存在，请重新登录！");
            }
        }

        //清空密码计数
        //redisTemplate.delete(String.format(ERROR_TIMES_KEY_TEMPLATE, accountBean.getStr("JE_RBAC_ACCOUNT_ID")));
        redisTemplate.unlink(String.format(ERROR_TIMES_KEY_TEMPLATE, accountBean.getStr("JE_RBAC_ACCOUNT_ID")));
        checkPassword(accountBean.getStr("JE_RBAC_ACCOUNT_ID"), password);

        try {
            //登录需判断机构类型是 外部机构 还是 公司员工
            //该账号所属机构是外部机构
            if (!rbacAccountService.checkOrgTypeByAccountId(accountBean.getStr("JE_RBAC_ACCOUNT_ID"))) {
                String token = rbacLoginService.login(tenantId, deptId, accountBean, device, "1");
                return BaseRespResult.successResult(token, "登录成功！");
            }
            if (!Strings.isNullOrEmpty(deptId)) {
                //校验当前部门是否有效
                DynaBean deptBean = rbacDepartmentService.findById(deptId);
                if (deptBean == null) {
                    return BaseRespResult.errorResult("获取人员部门异常！");
                }
                //判断该部门人员 是否允许访问系统：查找部门账号表是否存在
                DynaBean accountDeptBean = rbacLoginService.findAccountDept(accountBean.getStr("JE_RBAC_ACCOUNT_ID"), deptId);
                if (accountDeptBean == null || accountDeptBean.getStr("SY_STATUS").equals("0")) {
                    return BaseRespResult.errorResult("该人员部门未开通访问权限，请重新选择！");
                }
                String token = rbacLoginService.login(tenantId, deptId, accountBean, device, "1");
                return BaseRespResult.successResult(token, "登录成功！");
            }

            List<Map<String, Object>> departments = rbacLoginService.checkDepartment(accountBean);
            if (departments == null) {
                return BaseRespResult.errorResult("获取人员部门异常！");
            }
            if (departments.size() > 1) {
                return BaseRespResult.successResult(departments, "5001", "请选择部门！");
            }

            deptId = (String) departments.get(0).get("id");
            String token = rbacLoginService.login(tenantId, deptId, accountBean, device, "1");
            initUserSecretContext(request);
            return BaseRespResult.successResult(token, "登录成功！");
        } catch (LoginException e) {
            return BaseRespResult.errorResult(e.getMessage());
        } catch (AccountException e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
    }

    @RequestMapping(value = {"/logout"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult<String> logout(HttpServletRequest request) {
        //记录账号登录类型
        DynaBean accountBean = new DynaBean();
        accountBean.set("JE_RBAC_ACCOUNT_ID", SecurityUserHolder.getCurrentAccount().getId());
        accountBean.set("ACCOUNT_NAME", SecurityUserHolder.getCurrentAccount().getName());
        accountBean.set("ACCOUNT_CODE", SecurityUserHolder.getCurrentAccount().getCode());
        rbacLoginLogService.saveLoginLog(SecurityUserHolder.getCurrentAccount().getDeptId(), accountBean, "pc", "3");
        boolean success = rbacLoginService.logout();
        if (!success) {
            return BaseRespResult.successResult("注销成功！");
        }
        return BaseRespResult.successResult("注销失败！");
    }

    private void checkPassword(String accountId, String password) {
        //判断密码是否和当前校验规则，如果不符合，则设置重置密码标志
        String enablePasswordSecurityValid = systemSettingRpcService.findSettingValue("JE_REGEXP_ENABLE");
        if (!"1".equals(enablePasswordSecurityValid)) {
            if (redisTemplate.hasKey(String.format(USER_NEED_MODIFY_PASSWORD_TEMPALTE, accountId))) {
                redisTemplate.unlink(String.format(USER_NEED_MODIFY_PASSWORD_TEMPALTE, accountId));
            }
            return;
        }
        String num = systemSettingRpcService.findSettingValue("REGEXP_NUMBER");
        if (Strings.isNullOrEmpty(num)) {
            num = "6";
        }
        String regexp = systemSettingRpcService.findSettingValue("REGEXP");
        if (("complex".equals(regexp) && !rbacAccountService.validComplex(password, num))
                || ("common".equals(regexp) && !rbacAccountService.validMedium(password, num))
                || ("simple".equals(regexp) && !rbacAccountService.validSimple(password, num))) {
            redisTemplate.opsForValue().set(String.format(USER_NEED_MODIFY_PASSWORD_TEMPALTE, accountId), "1");
        }
    }

    /**
     * 获取账号部门列表
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/getAccountDeptTree"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getAccountDeptTree(HttpServletRequest request) throws LoginException {
        String accountId = getStringParameter(request, "accountId");
        String tenantId = getStringParameter(request, "tenantId");

        if (Strings.isNullOrEmpty(accountId)) {
            return BaseRespResult.errorResult("请选择要登录的账号！");
        }

        if (Strings.isNullOrEmpty(tenantId)) {
            tenantId = SecurityUserHolder.getCurrentAccountTenantId();
        }

        DynaBean accountBean = accountRpcService.findAccountById(accountId);
        if (accountBean == null) {
            return BaseRespResult.errorResult("账号不存在，请检查！");
        }

        DynaBean orgBean = rbacOrganizationService.findById(accountBean.getStr("SY_ORG_ID"));
        if (OrgType.DEPARTMENT_ORG_ID.getCode().equals(orgBean.getStr("JE_RBAC_ORG_ID"))) {
            List<Map<String, Object>> departments = rbacLoginService.checkDepartment(accountBean);
            if (departments == null) {
                return BaseRespResult.errorResult("获取人员部门异常！");
            }
            if (departments.size() >= 1) {
                return BaseRespResult.successResult(accountRpcService.getAccountDeptTreeNode(departments));
            }
        } else {
            List<String> deptList = accountRpcService.findAccountDeptIds(tenantId, accountId);
            if (deptList != null && deptList.size() == 1) {
                DynaBean org = rbacOrganizationService.findById(deptList.get(0));
                List<Map<String, Object>> departments = new ArrayList<>();
                Map<String, Object> orgDept = new HashMap<>();
                orgDept.put("id", deptList.get(0));
                orgDept.put("name", org.getStr("ORG_NAME"));
                departments.add(orgDept);
                return BaseRespResult.successResult(accountRpcService.getAccountDeptTreeNode(departments));
            }
        }
        return BaseRespResult.errorResult("获取人员部门异常！");
    }

    /***
     * 账号切换部门
     * @param request
     * @return
     */
    @RequestMapping(value = {"/switchDept"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult<String> switchDept(HttpServletRequest request) {
        String accountId = getStringParameter(request, "accountId");
        String deptId = getStringParameter(request, "deptId");
        String tenantId = getStringParameter(request, "tenantId");

        if (Strings.isNullOrEmpty(accountId)) {
            return BaseRespResult.errorResult("请选择要登录的账号！");
        }
        if (Strings.isNullOrEmpty(deptId)) {
            return BaseRespResult.errorResult("请选择部门！");
        }
        if (Strings.isNullOrEmpty(tenantId)) {
            boolean enableSaas = SpringContextHolder.getBean("enableSaas");
            tenantId = "";
            if (enableSaas) {
                tenantId = SecurityUserHolder.getCurrentAccountTenantId();
            }
        }

        DynaBean accountBean = accountRpcService.findAccountById(accountId);
        if (accountBean == null) {
            return BaseRespResult.errorResult("账号不存在，请检查！");
        }

//        DynaBean tenantRelationBean = null;
//        if (!Strings.isNullOrEmpty(tenantId)) {
//            tenantRelationBean = tenantRelationRpcService.findTenantRelation(accountBean.getStr("JE_RBAC_ACCOUNT_ID"), tenantId);
//            if (tenantRelationBean == null) {
//                return BaseRespResult.errorResult("租户或账号不存在！");
//            }
//        }

        DynaBean orgBean = rbacOrganizationService.findById(accountBean.getStr("SY_ORG_ID"));

        //校验当前部门是否有效
        DynaBean deptBean = rbacDepartmentService.findById(deptId);
        if (deptBean == null && OrgType.DEPARTMENT_ORG_ID.getCode().equals(orgBean.getStr("JE_RBAC_ORG_ID"))) {
            return BaseRespResult.errorResult("获取人员部门异常！");
        }
        //判断该部门人员 是否允许访问系统：查找部门账号表是否存在
        DynaBean accountDeptBean = rbacLoginService.findAccountDept(accountId, deptId);
        if (accountDeptBean == null || accountDeptBean.getStr("SY_STATUS").equals("0")) {
            return BaseRespResult.errorResult("该人员部门未开通访问权限，请重新选择！");
        }
        String newToken = rbacLoginService.login(tenantId, deptId, accountBean, "PC", "1");
        if (!Strings.isNullOrEmpty(newToken)) {
            return BaseRespResult.successResult(newToken, "登录成功！");
        }
        return BaseRespResult.successResult("登录失败，请检查！");
    }

    private void setTenantContext(DynaBean tenantRelationBean) {
        DynaTenant tenant = new DynaTenant();
        tenant.setId(tenantRelationBean.getStr("SY_TENANT_ID"));
        tenant.setName(tenantRelationBean.getStr("SY_TENANT_NAME"));
        DynaTenantContext.putTenant(tenant);
    }

}
